package com.yf.notify.modules.sms.utils;

import com.yf.ability.redis.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class SmsUtils {

    /**
     * 300秒有效期
     */
    private static final Long SMS_EXPIRY = 300L;

    /**
     * 验证码缓存前缀
     */
    private static final String SMS_PREFIX = "mobile:sms:";

    @Autowired
    private RedisService redisService;

    /**
     * 将数据存入redis以备校验
     * @param mobile
     * @param sms
     */
    public void save(String mobile, String sms){
        // 保存到缓存中
        redisService.set(appendKey(mobile), sms, SMS_EXPIRY);
    }

    /**
     * 校验是否正确
     * @param mobile
     * @param sms
     * @return
     */
    public boolean checkSms(String mobile, String sms) {
        String content = redisService.getString(appendKey(mobile));
        boolean check = content!=null && content.equals(sms);
        return check;
    }


    /**
     * 组合KEY
     * @param key
     * @return
     */
    public static String appendKey(String key){
        return new StringBuffer(SMS_PREFIX).append(key).toString();
    }

}
